// Copyright (c) 2010 god6or@gmail.com under MIT license.

package ul.comm

import java.io.{InputStream, OutputStream}
import collection.mutable.{ArrayBuffer}



abstract class SerialBase {
    
    /// returns list of available ports names
    def ports:List[String]
    /// returns number of available ports
    def nports:Int = ports.length

    /// port name
    var name:String = null
    
    /// opens port by name
    def open( name:String, bufSize:Int = 8192 ):Boolean
    /// closes port
    def close()
    
    /// get/set RX timeout (milliseconds)
    def timeoutRX: Int
    def timeoutRX_=(timeout:Int)
    
    /// get/set size of RX/TX buffers
    def bufRX: Int
    def bufRX_=(size:Int)
    def bufTX: Int
    def bufTX_=(size:Int)
    
    /// set port configuration
    def setup( baud:Int, bits:Int, stops:Double, parity:String )
    
    /// get/set baud rate
    def baud: Int
    def baud_=(baud:Int)
    
    /// get/set data bits
    def bits:Int
    def bits_=(b:Int)

    /// get/set stop bits
    def stops:Double
    def stops_=(s:Double)

    /// get/set parity
    def parity:String
    def parity_=(p:String)
    
    /// get/set port signals
    def DTR:Boolean
    def DTR_=(state:Boolean)
    def RTS:Boolean
    def RTS_=(state:Boolean)
    def CTS:Boolean
    def DCD:Boolean
    def RI:Boolean

    /// returns number of available bytes in RX buffer
    def availRX:Int
    /// waits for n input bytes for t * 0.1 milliseconds
    /// returns true if n bytes received, false if timeout occured
    def availWait( n:Int, t:Int ): Boolean = {
        var to = t
        while ( availRX < n && to > 0 ) {
            Thread.sleep(0, 100000)
            to -= 1
        }
        to > 0
    }
    /// waits for n input bytes for t * 0.1 milliseconds
    /// returns Array of n received bytes, null if timeout occured
    def readWait( n:Int, t:Int ): Array[Byte] = {
        availWait(n, t)
        read(n)
    }
    /// reads n bytes from RX buffer to array (available number if n == 0)
    def read(n:Int = 0):Array[Byte]
    /// writes bytes
    def write( bb:Seq[Byte] )
    
    /// flush RX/TX buffers
    def flushRX
    def flushTX
    def flush = { flushRX; flushTX }
}

